package com.huanong.controller.impl;

import com.huanong.common.grace.result.GraceJSONResult;
import com.huanong.controller.AdminControllerApi;
import com.huanong.pojo.Admin;
import com.huanong.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class AdminController implements AdminControllerApi {

    @Autowired
    private AdminService adminService;

    @Override
    public GraceJSONResult adminLogin(Admin admin, HttpServletRequest request, HttpServletResponse response) {
        if (admin.getAnAccount() == null || StringUtils.isEmpty(admin.getAnAccount()) ||
                admin.getAnAccount().length() < 6 || admin.getAnPassword().length() >= 15) {
            return GraceJSONResult.errorMsg("账号输入不合法");
        }
        if (admin.getAnPassword() == null || StringUtils.isEmpty(admin.getAnPassword())) {
            return GraceJSONResult.errorMsg("密码不能为空");
        }
        //从数据库获取账号数据
        Admin adminDb = adminService.queryPasswordByAccount(admin.getAnAccount());

         if (admin != null && admin.getAnPassword() != null && admin.getAnPassword().equals(adminDb.getAnPassword())) {
            //登录成功
            //1、将账号信息

             Cookie cookie = new Cookie("admin", adminDb.getAnId().toString());
             cookie.setPath("/");
             response.addCookie(cookie);
             adminDb.setAnPassword("");
            return GraceJSONResult.ok(adminDb);
        } else {
             return GraceJSONResult.errorMsg("密码或账号错误");
         }

    }

    @Override
    public GraceJSONResult adminRegister(Admin admin) {
        if (StringUtils.isEmpty(admin.getAnAccount()) || StringUtils.isEmpty(admin.getAnPassword()) ||
        StringUtils.isEmpty(admin.getAnName())) {
            return GraceJSONResult.errorMsg("请求参数失败");
        }
        admin.setAnTime(new Date());
        adminService.register(admin);
        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult adminCheckAccount(String adAccount) {
        //验证参数是否正确
        if (StringUtils.isEmpty(adAccount)) {
            return GraceJSONResult.errorMsg("参数错误");
        }
        //验证
        boolean checkAccount = adminService.isCheckAccount(adAccount);
        if (checkAccount) {
            return GraceJSONResult.ok();
        } else {
            return GraceJSONResult.error();
        }
    }
}
